<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    ini_set('display_errors', 1); // 开启错误显示
    error_reporting(E_ALL); // 显示所有错误

    $rawInput = file_get_contents("php://input"); // 获取原始请求体
    $data = json_decode($rawInput, true); // 解析 JSON 数据

    // 检查 JSON 数据是否有效
    if (!$data || !is_array($data)) {
        echo json_encode(array("success" => false, "message" => "JSON 数据解析失败"));
        exit;
    }

    // 提取字段并去除多余的空格
    $username = isset($data['username']) ? trim($data['username']) : '';
    $password = isset($data['password']) ? trim($data['password']) : '';
    $confirmPassword = isset($data['confirmPassword']) ? trim($data['confirmPassword']) : '';
    $email = isset($data['email']) ? filter_var(trim($data['email']), FILTER_VALIDATE_EMAIL) : false;
    $school = isset($data['school']) ? trim($data['school']) : '';
    $phone = isset($data['phone']) ? trim($data['phone']) : '';
    $classRoom = isset($data['classRoom']) ? trim($data['classRoom']) : '';

    // 校验字段完整性
    if (empty($username) || empty($password) || empty($email) || empty($school) || empty($phone) || empty($classRoom)) {
        echo json_encode(array("success" => false, "message" => "所有字段均为必填项"));
        exit;
    }

    // 校验密码一致性
    if ($password !== $confirmPassword) {
        echo json_encode(array("success" => false, "message" => "密码和确认密码不一致"));
        exit;
    }

    // 校验邮箱格式
    if (!$email) {
        echo json_encode(array("success" => false, "message" => "请输入有效的邮箱"));
        exit;
    }

    // 校验手机号格式
    if (!preg_match("/^[1][3-9][0-9]{9}$/", $phone)) {
        echo json_encode(array("success" => false, "message" => "手机号格式不正确"));
        exit;
    }

    // 连接数据库
    $servername = "localhost";
    $db_username = "root"; // 数据库用户名
    $db_password = "123456"; // 数据库密码
    $dbname = "test"; // 数据库名称

    $conn = new mysqli($servername, $db_username, $db_password, $dbname);

    // 检查数据库连接
    if ($conn->connect_error) {
        echo json_encode(array("success" => false, "message" => "数据库连接失败: " . $conn->connect_error));
        exit;
    }

    try {
        // 检查用户名是否已被注册
        $sqlNameCheck = 'SELECT * FROM student WHERE username = ?';
        $stmt = $conn->prepare($sqlNameCheck);
        $stmt->bind_param('s', $username);
        $stmt->execute();
        $res = $stmt->get_result();

        if ($res->num_rows > 0) {
            echo json_encode(array("success" => false, "message" => "用户名已被注册，请更换用户名"));
            exit;
        }

        // 插入新用户
        $sqlInsert = 'INSERT INTO student (username, password, email, school, phone, classRoom) VALUES (?, ?, ?, ?, ?, ?)';
        $stmt = $conn->prepare($sqlInsert);

        if ($stmt) {
            $hashedPassword = password_hash($password, PASSWORD_BCRYPT); // 对密码进行加密
            $stmt->bind_param('ssssss', $username, $hashedPassword, $email, $school, $phone, $classRoom);

            if ($stmt->execute()) {
                echo json_encode(array("success" => true, "message" => "注册成功"));
            } else {
                echo json_encode(array("success" => false, "message" => "数据插入失败: " . $stmt->error));
            }
        } else {
            echo json_encode(array("success" => false, "message" => "数据预处理失败: " . $conn->error));
        }
    } catch (Exception $e) {
        echo json_encode(array("success" => false, "message" => "系统错误: " . $e->getMessage()));
    } finally {
        if (isset($stmt)) $stmt->close(); // 关闭数据库语句
        $conn->close(); // 关闭数据库连接
    }
} else {
    echo json_encode(array("success" => false, "message" => "无效的请求方法"));
}
?>
